"""
Verify Docmee Native API
Test docmee API using direct HTTP requests to understand the authentication flow
"""
import os
import sys
import json

# Add project root to path
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from dotenv import load_dotenv
load_dotenv()

from src.llm.aippt_app.utils.api_client import AIPPTAPIClient
from src.llm.aippt_app.config.aippt_config import AIPPTConfig

def print_separator(title):
    print("\n" + "=" * 70)
    print(f"  {title}")
    print("=" * 70)

def print_test_result(test_name, success, message="", data=None):
    status = "[PASS]" if success else "[FAIL]"
    print(f"\n{status} {test_name}")
    if message:
        print(f"  Message: {message}")
    if data:
        print(f"  Data: {json.dumps(data, indent=2, ensure_ascii=False)[:500]}")

def main():
    print("\n" + "*" * 70)
    print("  Docmee Native API Verification")
    print("*" * 70)

    # Check configuration
    print_separator("Configuration Check")
    print(f"Base URL: {AIPPTConfig.BASE_URL}")
    print(f"Token: {AIPPTConfig.TOKEN[:20]}..." if AIPPTConfig.TOKEN else "Token: NOT SET")

    if not AIPPTConfig.TOKEN or AIPPTConfig.TOKEN.startswith("your_"):
        print("\n[ERROR] AIPPT_TOKEN not properly configured in .env file")
        return

    # Initialize client
    try:
        client = AIPPTAPIClient()
        print("[OK] API Client initialized successfully")
    except Exception as e:
        print(f"[ERROR] Failed to initialize client: {e}")
        return

    test_results = []

    # Test 1: Get Template Options
    print_separator("Test 1: Get Template Options")
    try:
        response = client.get_template_options()
        if response.get("code") == 0:
            print_test_result("Get Template Options", True, "Successfully retrieved options", response.get("data"))
            test_results.append(("Template Options", True))
        else:
            print_test_result("Get Template Options", False, f"API Error: {response.get('message')}", response)
            test_results.append(("Template Options", False))
    except Exception as e:
        print_test_result("Get Template Options", False, str(e))
        test_results.append(("Template Options", False))

    # Test 2: Get Random Templates
    print_separator("Test 2: Get Random Templates")
    try:
        response = client.get_random_templates(count=3)
        if isinstance(response.get("data"), list) and len(response.get("data", [])) > 0:
            templates = response["data"]
            print_test_result("Get Random Templates", True, f"Retrieved {len(templates)} templates")
            print(f"\nFirst template:")
            print(f"  ID: {templates[0].get('id')}")
            print(f"  Name: {templates[0].get('name') or templates[0].get('subject')}")
            print(f"  Category: {templates[0].get('category')}")
            print(f"  Style: {templates[0].get('style')}")
            test_results.append(("Random Templates", True))
        else:
            print_test_result("Get Random Templates", False, "No templates returned", response)
            test_results.append(("Random Templates", False))
    except Exception as e:
        print_test_result("Get Random Templates", False, str(e))
        test_results.append(("Random Templates", False))

    # Test 3: Get Generation Options (V2)
    print_separator("Test 3: Get Generation Options (V2)")
    try:
        response = client.get_generation_options()
        if response.get("code") == 0:
            data = response.get("data", {})
            print_test_result("Generation Options", True, "Successfully retrieved options")
            print(f"\nAvailable options:")
            for key in data.keys():
                print(f"  - {key}")
            test_results.append(("Generation Options", True))
        else:
            print_test_result("Generation Options", False, f"API Error: {response.get('message')}", response)
            test_results.append(("Generation Options", False))
    except Exception as e:
        print_test_result("Generation Options", False, str(e))
        test_results.append(("Generation Options", False))

    # Test 4: Create Task
    print_separator("Test 4: Create Task")
    try:
        response = client.create_task(
            task_type=1,
            content="AI and Machine Learning in Modern Education"
        )
        if response.get("code") == 0:
            task_id = response.get("data", {}).get("taskId")
            print_test_result("Create Task", True, f"Task created: {task_id}")
            test_results.append(("Create Task", True))
        else:
            print_test_result("Create Task", False, f"API Error: {response.get('message')}", response)
            test_results.append(("Create Task", False))
    except Exception as e:
        print_test_result("Create Task", False, str(e))
        test_results.append(("Create Task", False))

    # Test 5: List PPT Works
    print_separator("Test 5: List PPT Works")
    try:
        response = client.list_pptx(current=1, size=5)
        if response.get("code") == 0:
            data = response.get("data", {})
            total = data.get("total", 0)
            records = data.get("records", [])
            print_test_result("List PPT Works", True, f"Found {total} total works, {len(records)} in this page")
            if records:
                print(f"\nFirst PPT:")
                print(f"  ID: {records[0].get('id')}")
                print(f"  Title: {records[0].get('title')}")
                print(f"  Created: {records[0].get('createTime')}")
            test_results.append(("List PPT Works", True))
        else:
            print_test_result("List PPT Works", False, f"API Error: {response.get('message')}", response)
            test_results.append(("List PPT Works", False))
    except Exception as e:
        print_test_result("List PPT Works", False, str(e))
        test_results.append(("List PPT Works", False))

    # Print Summary
    print_separator("Test Summary")
    passed = sum(1 for _, success in test_results if success)
    total = len(test_results)

    for test_name, success in test_results:
        status = "[PASS]" if success else "[FAIL]"
        print(f"{status} {test_name}")

    print(f"\nTotal: {passed}/{total} tests passed")
    print(f"Success Rate: {passed/total*100:.1f}%")

    if passed == total:
        print("\n[SUCCESS] All tests passed! Docmee API is working correctly.")
    elif passed > 0:
        print(f"\n[PARTIAL] {passed} tests passed, {total-passed} failed.")
    else:
        print("\n[FAILURE] All tests failed. Please check network and configuration.")

if __name__ == "__main__":
    main()
